package com.gec.yhzh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gec.yhzh.entity.Department;
import com.gec.yhzh.entity.Doctor;
import com.gec.yhzh.entity.DoctorDTO;
import com.gec.yhzh.service.IDepartmentService;
import com.gec.yhzh.service.IDoctorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 医生 前端控制器
 * </p>
 *
 * @author jerry
 * @since 2025-03-10
 */
@RestController
@RequestMapping("/doctor")
public class DoctorController {
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IDepartmentService departmentService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/query")
    public String queryDoctors() throws JsonProcessingException {
        Map<String, Object> result = new HashMap<>();
        List<Doctor> doctorList = doctorService.list();
        List<DoctorDTO> doctorDTOList = new ArrayList<>();

        if (doctorList == null || doctorList.isEmpty()) {
            result.put("flag", false);
            result.put("message", "医生列表为空");
            return objectMapper.writeValueAsString(result);
        }

        for (Doctor doctor : doctorList) {
            DoctorDTO doctorDTO = new DoctorDTO();
            BeanUtils.copyProperties(doctor, doctorDTO); // 修正参数顺序
            Integer departmentId = doctor.getDepartmentId();
            if (departmentId != null) {
                Department department = departmentService.getById(departmentId);
                if (department != null) {
                    doctorDTO.setDepartmentName(department.getName());
                }
            }
            doctorDTOList.add(doctorDTO);
        }

        result.put("flag", true);
        result.put("list", doctorDTOList);
        return objectMapper.writeValueAsString(result);
    }
    @GetMapping(value = "/selectById")
    public String selectById(Integer id) throws JsonProcessingException {
        Map<String, Object> result = new HashMap<>();
        Doctor doctor = doctorService.getById(id);
        if (doctor == null) {
            result.put("flag", false);
            result.put("message", "医生不存在");
            return objectMapper.writeValueAsString(result);
        }
        result.put("flag", true);
        result.put("doctor", doctor);
        return objectMapper.writeValueAsString(result);
    }
}